<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Ernest Dey
 * Date: 4/14/12
 * Time: 1:32 PM
 */
require_once 'Session.php';

define('URL', 'http://localhost/e-major/');

class Database extends Session
{
    private $con = null;
    private $isConnected = false;

    public function __construct()
    {
        $config = parse_ini_file('config/config.ini');
        $this->con = mysql_connect($config['host'], $config['username'], $config['password']);
        if ($this->con) {
            $this->isConnected = true;
        }

        if ($this->isConnected) {
            mysql_select_db($config['database'], $this->con);
        }
    }

    public function getData($post)
    {
        $result = $this->findById($post['table'], false, $post['id']);
        echo json_encode($result);
    }

    public function find($table, $argument = false)
    {
        $sql = "SELECT * FROM `{$table}` ";
        $sql .= $argument != false ? $argument : '';
        //var_dump($sql);
        $result = mysql_query($sql);
        if (mysql_num_rows($result) > 0) {
            return $result;
        }
    }


    public function findById($table, $argument = false, $id = null)
    {
        $sql = "SELECT * FROM `{$table}` WHERE `id` = {$id} ";
        $sql .= $argument != false ? $argument : '';
        $result = mysql_query($sql);
        if (mysql_num_rows($result) > 0) {
            return mysql_fetch_object($result);
        }
    }

    protected function insert($table = null, $data = null)
    {
        if (!is_null($table) && !is_null($data)) {
            if ($this->isEmpty($data) !== true) {
                return array(
                    'msg' => "This form can't be empty",
                    'type' => 'msg_error'
                );
            }

            if (is_array($data)) {
                $keys = $this->applyUserFunction(array_keys($data), false, false, false);
                $values = $this->applyUserFunction(array_values($data), false, true, true);
                $sql = "INSERT INTO {$table} ( " . implode(", ", $keys) . ")  VALUES (";
                $sql .= rtrim($values, ", ");
                $sql .= ")";
                //var_dump($sql);
                mysql_query($sql);
                $result = array();
                if (mysql_affected_rows() == 1) {
                    $result['msg'] = 'Data successfully saved';
                    $result['type'] = 'msg_ok';
                    $result['uid'] = mysql_insert_id();
                } else {
                    $result['msg'] = mysql_error();
                    $result['type'] = 'msg_error';
                }
                return $result;
            }
        } // Checks tablel and array data.
    }

    private function applyUserFunction($array, $escapeMysqlKey = false, $escapeMysqlValue = false, $append = false)
    {
        $preparedValues = ($append === true) ? '' : array();
        if (is_array($array)) {
            foreach ($array as $value) {
                if ($escapeMysqlValue) {
                    $value = mysql_real_escape_string($value);
                }

                if ($escapeMysqlKey) {
                    $value = "`{$value}`";
                }

                if ($append) {
                    $preparedValues .= "  '$value',  ";
                } else {
                    $preparedValues[] = $value;
                }

            }
        }
        return $preparedValues;
    }

    protected function escapeValue($value)
    {
        return mysql_real_escape_string($value);
    }

    protected function authenticate($array)
    {
        //var_dump($array);
        if (is_array($array)) {
            if (array_key_exists('username', $array) && array_key_exists('password', $array)) {
                $username = $this->escapeValue($array['username']);
                $password = $this->escapeValue(sha1($array['password']));
                $result = $this->find('users', "WHERE `username` = '{$username}' AND `password` = '{$password}' ");
                //var_dump($result); exit;
                if (is_resource($result)) {
                    $found = mysql_fetch_object($result);
                    Session::set('role', $found->role);
                    Session::set('uname', $found->username);
                    Session::set('uid', $found->id);
                    return $found;
                } else {
                    return '<b>USER NOT FOUND</b>';
                }
            }
        }
    }

    protected function redirect($loc = null)
    {
        if (!is_null($loc)) {
            header("Location: " . URL . $loc);
            exit;
        }
    }

    protected function getUserRole()
    {
        if (isset($_SESSION)) {
            return Session::get('role');
        } else {
            return false;
        }
    }

    public function checkUser()
    {
        if (!$this->getUserRole()) {
            $this->logout();
        }
    }

    public function isAdmin()
    {
        $role = $this->getUserRole();
        if ($role != 'admin' && $role != 'counselor') {
            $this->redirect('./');
        }
    }

    protected function logout()
    {
        Session::dologout();
    }

    private function isEmpty($array)
    {
        $error = array();
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                if (empty($array[$key])) {
                    $error[$key] = " Error";
                }
            }
        }
        return !empty($error) ? $error : true;
    }

    protected function update($table = null, $id = null, $data = null)
    {
        if (!is_null($table) && !is_null($id) && !is_null($data)) {
            $updateQuery = $this->formatDataForSave($data);
            $sql = "UPDATE `$table` SET " . $updateQuery;
            $sql .= " WHERE id = " . $this->escapeValue(intval($id));
            mysql_query($sql);
            $result = array();
            if (mysql_affected_rows() == 1) {
                $result['msg'] = 'Data successfully Update';
                $result['type'] = 'msg_ok';
            } else {
                $result['msg'] = mysql_error();
                $result['type'] = 'msg_error';
            }
            return $result;
        }
    }

    private function formatDataForSave($data)
    {
        $stringBuffer = '';
        foreach ($data as $key => $value) {
            $value = $this->escapeValue($value);
            $stringBuffer .= "`$key` = '$value', ";
        }
        return rtrim($stringBuffer, ', ');
    }

    public function delete($id = null, $table = null)
    {
        if (!is_null($id) && !is_null($table)) {
            $sql = "DELETE FROM `{$table}` WHERE `id` = " . intval($id) . " LIMIT 1";
            mysql_query($sql);
            $result = array();
            if (mysql_affected_rows() == 1) {
                $result['msg'] = 'Data successfully Deleted';
                $result['type'] = 'msg_ok';
            } else {
                $result['msg'] = mysql_error();
                $result['type'] = 'msg_error';
            }
            return $result;
        }
    }
}
